from django.shortcuts import render
from book.models import BookInfo, PeopleInfo
from django.http import HttpResponse, JsonResponse
import json
from django.shortcuts import redirect
from django.views.generic import View
def index(requset):

    return HttpResponse('ok')


def goods(requset, book_id, id):

    return HttpResponse(book_id)


# from表单数据
def froms(request):

    s = request.GET.get('name')
    print(s)
    return HttpResponse(s)

# 返回json数据

def Jsons(request):
    s_b = request.body
    s_str = s_b.decode()
    print(s_str)
    s_str = eval(json.loads(s_str))
    print(s_str, type(s_str))
    s_dict = json.dumps(json.dumps(s_str))
    print(s_dict, type(s_dict))

    print('===================================')
    st = '{"name":"yanzilang"}'
    st_dict = json.loads(st)
    print(st_dict, type(st_dict))
    st_dump = json.dumps(st_dict)
    print(st_dump, type(st_dump))
    #print(s_dict, type(s_dict))
    #s = s_dict.get('name')
    #s_json = eval(json.dumps(s_dict))
    #print(s_dict, type(s_dict))
    return HttpResponse(st_dump)

# jsonpsoen

def json_retuen(request):
    '''返回json数据'''


    user_info = BookInfo.objects.get(id=1).peopleinfo_set.all()
    print(user_info)
    user_dict = {}
    a = 0
    for i in user_info:
        a += 1
        user_dict[a] = i.name

    print(user_dict)

    return JsonResponse(user_dict)





def red(request):

    return redirect('/json/')




# 设置cookie
def cookie(request):
    response = HttpResponse('ok')
    response.set_cookie('name', 'yanziliang', max_age=20)

    return response


# 读取cookie
def read_cookie(request):
    cookie = request.COOKIES.get('name')
    print(cookie)

    return HttpResponse(cookie)

# 删除cookie
def delete_cookie(request):
    response = HttpResponse('delete_cookie')
    response.delete_cookie('name')

    return response



# 设置session

def set_session(request):
    request.session['name'] = 'yanziliang'

    return HttpResponse('set_session')


# 获得session
def get_session(request):

    sesion = request.session.get('name')


    return HttpResponse(sesion)





# 验证手机号
class Moble_Check(View):

    def get(self, request, phone):
        print(phone)
        return HttpResponse(phone)
